package me.ree.zkproduct.controller;

import me.ree.zkproduct.entity.Orders;
import me.ree.zkproduct.service.IOrdersService;
import me.ree.zkproduct.util.Resp;
import me.ree.zkproduct.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author ree
 * @since 2024-05-17
 */
@RestController
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    private IOrdersService ordersServiceImpl;


    // 创建新的订单
    @PostMapping("/")
    public Resp<String> createOrder(@RequestBody Orders orders) {
        if (StringUtils.isEmpty(orders.getProductCode())) {
            return Resp.fail("订单的产品代码不能为空");
        }
        if (orders.getGmtCreate() == null || orders.getGmtCreate().longValue() == 0L) {
            orders.setGmtCreate(System.currentTimeMillis());
        }
        if (orders.getGmtModified() == null || orders.getGmtModified().longValue() == 0L) {
            orders.setGmtModified(System.currentTimeMillis());
        }
        boolean result = ordersServiceImpl.save(orders);
        if (result) {
            return Resp.ok("ok");
        }

        return Resp.fail("新增订单失败");
    }

    // 获取所有订单
    @GetMapping("/")
    public Resp<List<Orders>> getAllOrders() {
        List<Orders> ordersList = ordersServiceImpl.list();
        return Resp.ok(ordersList);
    }

    // 根据 ID 获取订单
    @GetMapping("/id/{id}")
    public Resp<Orders> getOrderById(@PathVariable Long id) {
        Orders orders = ordersServiceImpl.getById(id);
        return Resp.ok(orders);
    }

    // 更新订单
    @PutMapping("/")
    public Resp<Boolean> updateOrder(@RequestBody Orders orders) {
        // 更新的时候不能修改创建时间
        if (orders.getGmtCreate() != null) {
            orders.setGmtCreate(null);
        }
        // 更新时间为空时，自动赋值
        if (orders.getGmtModified() == null || orders.getGmtModified().longValue() == 0L) {
            orders.setGmtModified(System.currentTimeMillis());
        }
        boolean result = ordersServiceImpl.updateById(orders);
        return Resp.ok(result);
    }

    // 删除订单
    @DeleteMapping("/{id}")
    public Resp<Boolean> deleteOrder(@PathVariable Long id) {
        boolean result = ordersServiceImpl.removeById(id);
        return Resp.ok(result);
    }
}
